package com.atguigu.grainmall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.grainmall.ware.feign.MemberFeignService;
import com.atguigu.grainmall.ware.vo.FareVo;
import com.atguigu.grainmall.ware.vo.MemberAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.grainmall.ware.dao.WareInfoDao;
import com.atguigu.grainmall.ware.entity.WareInfoEntity;
import com.atguigu.grainmall.ware.service.WareInfoService;
import org.springframework.util.StringUtils;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 模糊检索
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<WareInfoEntity> wrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.eq(WareInfoEntity::getId,key)
                    .or().like(WareInfoEntity::getName,key)
                    .or().like(WareInfoEntity::getAddress,key)
                    .or().like(WareInfoEntity::getAreacode,key);
        }
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据用户收货地址计算获取运费
     *
     * @param addrId
     * @return
     */
    @Override
    public FareVo getFare(Long addrId) {
        FareVo fareVo = new FareVo();
        // 远程获取用户收获地地址
        R addrInfo = memberFeignService.addrInfo(addrId);
        MemberAddressVo data = addrInfo.getData("memberReceiveAddress",new TypeReference<MemberAddressVo>() {}); //memberReceiveAddress
        if (data != null){
            String phone = data.getPhone();
            String fare = phone.substring(phone.length() - 1, phone.length());
            BigDecimal decimalFare = new BigDecimal(fare);
            fareVo.setAddress(data);
            fareVo.setFare(decimalFare);
            return fareVo;
        }
        return null;
    }

}
